package com.wmh.baseservice.user.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wmh.baseservice.common.annotation.parameterverify.ParameterVerify;
import com.wmh.baseservice.common.utils.CommUtil;
import com.wmh.baseservice.common.utils.encrypt.Base64Util;
import com.wmh.baseservice.common.utils.returnbody.ResultCodeInfo;
import com.wmh.baseservice.common.utils.returnbody.ReturnBody;
import com.wmh.baseservice.system.pojo.SysParams;
import com.wmh.baseservice.system.service.SysParamsService;
import com.wmh.baseservice.user.pojo.UsAfterSaleApply;
import com.wmh.baseservice.user.pojo.UsGroupGoodsOrder;
import com.wmh.baseservice.user.pojo.UsVegetableOrder;
import com.wmh.baseservice.user.service.UsAfterSaleApplyService;
import com.wmh.baseservice.user.service.UsGoodsOrderService;
import com.wmh.baseservice.user.service.UsGroupGoodsOrderService;
import com.wmh.baseservice.user.service.UsVegetableOrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "用户端-售后相关")
@RestController
@RequestMapping(value = "user/afterSale", produces = "text/plain;charset=utf-8")
public class UsAfterSaleController {

    @Resource
    private UsGoodsOrderService usGoodsOrderService;
    @Resource
    private UsGroupGoodsOrderService usGroupGoodsOrderService;
    @Resource
    private HttpServletRequest request;
    @Resource
    private UsAfterSaleApplyService usAfterSaleApplyService;
    @Resource
    private SysParamsService sysParamsService;
    @Resource
    private UsVegetableOrderService usVegetableOrderService;


    @ApiOperation("提交售后申请")
    @PostMapping("add")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = String.class, name = "orderNum", value = "订单编号", required = true),
            @ApiImplicitParam(paramType = "query", dataTypeClass = Integer.class, name = "type", value = "1普通商品 2团购商品 3平台商品", required = true),
            @ApiImplicitParam(paramType = "query", dataTypeClass = Integer.class, name = "reason", value = "申请理由", required = true),
            @ApiImplicitParam(paramType = "query", dataTypeClass = Integer.class, name = "status", value = "1:仅退款 2：退货退款", required = true),
            @ApiImplicitParam(paramType = "query", dataTypeClass = String.class, name = "content", value = "详细描述", required = true),
            @ApiImplicitParam(paramType = "query", dataTypeClass = String.class, name = "img", value = "图片凭证", required = true),
    })
    @ParameterVerify(notNull = {"orderNum", "type", "reason", "status"})
    public String add(String orderNum, Integer type, String reason, Integer status, String img, String content) {
        Long usId = (Long) request.getAttribute("usId");
        UsAfterSaleApply usAfterSaleApply = new UsAfterSaleApply().setStatus(0);
        int count = usAfterSaleApplyService.count(new QueryWrapper<UsAfterSaleApply>().eq(UsAfterSaleApply.ORDER_NUM, orderNum).in(UsAfterSaleApply.STATUS, 0, 1, 2));
        if (count != 0) {
            return ReturnBody.error("售后状态错误");
        }
        Map<String, Object> map = new HashMap<>();
        SysParams sysParams = sysParamsService.getByIdForUpdate(8L);
        if (!CommUtil.checkNull(sysParams)) {
            return ReturnBody.error(ResultCodeInfo.PARAM_ERROR);
        }
        map.put("day", sysParams.getValue());
        UsVegetableOrder usVegetableOrder = null;
        UsGroupGoodsOrder usGroupGoodsOrder = null;
        if (type == 1) {
            usVegetableOrder = usVegetableOrderService.getOneForUpdate(new QueryWrapper<UsVegetableOrder>().eq(UsVegetableOrder.ORDER_NUM, orderNum));
            if (!CommUtil.checkNull(usVegetableOrder)) {
                return ReturnBody.error("订单不存在");
            }
            if (usVegetableOrder.getStatus() <= 0) {
                return ReturnBody.error("订单状态错误");
            }
            if (usVegetableOrder.getAfterSalesStatus() != 0) {
                return ReturnBody.error("订单售后状态错误");
            }
            if (CommUtil.checkNull(usVegetableOrder.getTakeTime())) {
                map.put("type", 1);
                map.put("orderNum", usVegetableOrder.getOrderNum());
                int hasOverdue = sysParamsService.hasOverdue(map);
                if (hasOverdue != 0) {
                    return ReturnBody.error("已超过最大售后期，无法申请售后服务");
                }
            }
            usAfterSaleApply.setRefundAmount(usVegetableOrder.getRealPrice());
            usVegetableOrder.setAfterSalesStatus(1);
        } else if (type == 2) {
            usGroupGoodsOrder = usGroupGoodsOrderService.getOneForUpdate(new QueryWrapper<UsGroupGoodsOrder>().eq(UsGroupGoodsOrder.ORDER_NO, orderNum));
            if (!CommUtil.checkNull(usGroupGoodsOrder)) {
                return ReturnBody.error("订单不存在");
            }
            if (usGroupGoodsOrder.getStatus() <= 0) {
                return ReturnBody.error("订单状态错误");
            }
            if (usGroupGoodsOrder.getAfterSaleStatus() != 0) {
                return ReturnBody.error("订单售后状态错误");
            }
            //售后类型是退货退款
            if (status == 2) {
                if (usGroupGoodsOrder.getStatus() == 1) {
                    return ReturnBody.error("该订单未发货，请选择仅退款");
                }
                if (usGroupGoodsOrder.getStatus() == 3) {
                    return ReturnBody.error("该订单未提货，请选择仅退款");
                }
            }
            //已收货情况下查询是否超过售后期
            if (CommUtil.checkNull(usGroupGoodsOrder.getDeliveryTime())) {
                map.put("type", 2);
                map.put("orderNum", usGroupGoodsOrder.getOrderNo());
                int hasOverdue = sysParamsService.hasOverdue(map);
                if (hasOverdue != 0) {
                    return ReturnBody.error("已超过最大售后期，无法申请售后服务");
                }
            }
            usGroupGoodsOrder.setAfterSaleStatus(1);
            BigDecimal amount=usGroupGoodsOrder.getRealPrice();
            if (CommUtil.checkNull(usGroupGoodsOrder.getFreightPrice())){
                amount=usGroupGoodsOrder.getRealPrice().subtract(usGroupGoodsOrder.getFreightPrice());
            }
            usAfterSaleApply.setRefundAmount(amount);
        }
        usAfterSaleApply.setRedundReason(reason);
        usAfterSaleApply.setType(type);
        usAfterSaleApply.setStatus(0);
        usAfterSaleApply.setUsId(usId);
        usAfterSaleApply.setContent(content);
        usAfterSaleApply.setOrderNum(orderNum);
        usAfterSaleApply.setRefundType(status);
        if (CommUtil.checkNull(img)) {
            String url = Base64Util.generateImage("order/", img);
            usAfterSaleApply.setImg(url);
        }
        usAfterSaleApplyService.add(usAfterSaleApply, usVegetableOrder, usGroupGoodsOrder);
        return ReturnBody.success();
    }

    @ApiOperation("售后详情")
    @PostMapping("detail")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = String.class, name = "订单编号", value = "orderNum", required = true),
    })
    @ParameterVerify(notNull = "orderNum")
    public String detail(String orderNum) {
        List<UsAfterSaleApply> usAfterSaleApplies = usAfterSaleApplyService.listForUpdate(new QueryWrapper<UsAfterSaleApply>().eq(UsAfterSaleApply.ORDER_NUM, orderNum));
        if (usAfterSaleApplies.size() == 0) {
            return ReturnBody.error("未查到售后相关信息");
        }
        usAfterSaleApplies.sort(Comparator.comparing(UsAfterSaleApply::getCreateTime).reversed());
        //返回最新的一条售后详情
        return ReturnBody.success(usAfterSaleApplies.get(0));
    }

    @ApiOperation("填写快递单号")
    @PostMapping("writeCourier")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = String.class, name = "courierNum", value = "快递单号", required = true),
            @ApiImplicitParam(paramType = "query", dataTypeClass = String.class, name = "orderNum", value = "订单号", required = true),
    })
    @ParameterVerify(notNull = "courierNum")
    public String writeCourier(String courierNum, String orderNum) {
        UsAfterSaleApply usAfterSale = usAfterSaleApplyService.getOneForUpdate(new QueryWrapper<UsAfterSaleApply>().eq(UsAfterSaleApply.ORDER_NUM, orderNum).eq(UsAfterSaleApply.STATUS, 1));
        if (!CommUtil.checkNull(usAfterSale)) {
            return ReturnBody.error("售后详单不存在");
        }
        usAfterSale.setCourierNumber(courierNum);
        if (!usAfterSaleApplyService.updateById(usAfterSale)) {
            return ReturnBody.error(ResultCodeInfo.SERVICE_EXCEPTION);
        }
        return ReturnBody.success();
    }
}
